# -*- coding: utf-8 -*-
from django import forms
from django.utils.translation import ugettext_lazy as _

from apps.registration.forms import RegistrationForm
from apps.registration.models import RegistrationProfile
from apps.perfil.models import Empresario
from apps.l10n.models import City, AdminArea

import re
################################################################################
first_dict = { 'maxlength': '30', 'id': 'nombre' }
last_dict = { 'maxlength': '30', 'id': 'apellido' }
email_dict = {'id':'email', }
username_dict = {'id':'username', }
password_dict = {'id' : 'password','name' : 'password', 'class' : 'password' }
empresario_dic = {'maxlength' : '12', 'id': 'codigo_empresario' }
date_dict = { 'id' : 'datepicker', 'autocomplete' : 'off' }
#pais_dict = {'id' : 'pais'}
depto_dict = {'id' : 'departamento'}
ciudad_dict = {'id' : 'ciudad'}
################################################################################
class UserProfileRegistrationForm(RegistrationForm):
    
    def __init__(self, *args, **kwargs):
        super(UserProfileRegistrationForm, self).__init__(*args, **kwargs)
        #self.fields['pais'].choices = [('', '----------')] + [(p.codigo, p.nombre) for p in Pais.objects.all().order_by('nombre')]
        #self.fields['departamento'].choices = [('','----------')] + [(d.codigo, d.nombre) for d in Departamento.objects.all().order_by('nombre')]
        self.fields['departamento'].choices = [('0','----------')] + [(d.id, d.name) for d in AdminArea.objects.filter(country__numcode=170).order_by('name')]
        self.fields['ciudad'].choices = [('0','----------')]    
    
    
    nombre = forms.CharField(widget=forms.TextInput(attrs=first_dict))
    apellido = forms.CharField(widget=forms.TextInput(attrs=last_dict))
    fecha_nacimiento = forms.DateField(widget=forms.TextInput(attrs=date_dict))
    cod_empresario = forms.IntegerField(widget=forms.TextInput(attrs=empresario_dic))
    telefono = forms.CharField(required=False)
    movil = forms.CharField(required=False)
    #pais = forms.ChoiceField(widget=forms.Select(attrs=pais_dict))
    departamento = forms.ChoiceField(widget=forms.Select(attrs=depto_dict))
    ciudad = forms.ModelChoiceField(City.objects, widget=forms.Select(attrs=ciudad_dict))
    

    email = forms.EmailField(widget=forms.TextInput(attrs=email_dict))
    # if you really don't want the extra validation you can use
    #email = forms.CharField(widget=forms.TextInput(attrs=email_dict))

    # if you want people to be able to see their passwords
    #password1 = forms.CharField(widget=forms.TextInput(attrs=password_dict))
    password1 = forms.CharField(widget=forms.PasswordInput(attrs=password_dict))

    # if you really don't want that id_ before the css id ...
    #username = forms.CharField(widget=forms.TextInput(attrs=username_dict))
    
    
    def clean_password1(self):
        password = str(self.cleaned_data.get('password1'))
        if len(password) < 6:
            raise forms.ValidationError(_(u'El minimo numero de carateres es 6'))
            
        return password
    
    
    def clean_cod_empresario(self):
        codigo = str(self.cleaned_data.get('cod_empresario'))
        if len(codigo) != 10 or re.search('1906', codigo) == None:
            raise forms.ValidationError(_(u'Debe ingresar un codigo de Empresario Amway valido. El mismo con el que ingresa a la pagina de Amway'))
            
        elif Empresario.objects.filter(cod_empresario__iexact=codigo):
            raise forms.ValidationError(_(u'Esta codigo de Empresario Amway ya se encuentra en uso. Por favor suministre un codigo de Empresario Amway diferente.'))      
            
        return codigo
    
    def save(self, profile_callback=None):
        new_user = RegistrationProfile.objects.create_inactive_user(username=self.cleaned_data['username'],
                                                                    password=self.cleaned_data['password1'], email=self.cleaned_data['email'],)

        new_user.first_name = self.cleaned_data['nombre']
        new_user.last_name = self.cleaned_data['apellido']
        new_user.save()
        
        ciudad = City.objects.select_related().get(id=int(self.cleaned_data['ciudad'].id))
        departamento = ciudad.admin_area
        pais = departamento.country
        
        new_profile = Empresario( user = new_user, nombre=self.cleaned_data['nombre'], apellido=self.cleaned_data['apellido'],
                                  fecha_nacimiento=self.cleaned_data['fecha_nacimiento'], cod_empresario=self.cleaned_data['cod_empresario'],
                                  telefono=self.cleaned_data['telefono'], movil=self.cleaned_data['movil'],
                                  pais=pais, departamento=departamento , ciudad=ciudad)       
        new_profile.save()
        return new_user
################################################################################
class EditProfileForm(forms.Form):
    
    def __init__(self, *args, **kwargs):
        super(EditProfileForm, self).__init__(*args, **kwargs)
        #self.fields['pais'].choices = [('', '----------')] + [(p.codigo, p.nombre) for p in Pais.objects.all().order_by('nombre')]
        self.fields['departamento'].choices = [('0','----------')] + [(d.id, d.name) for d in AdminArea.objects.filter(country__numcode=170).order_by('name')]
        self.fields['ciudad'].choices = [('0','----------')] 

    nombre = forms.CharField(widget=forms.TextInput(attrs=first_dict))
    apellido = forms.CharField(widget=forms.TextInput(attrs=last_dict))
    fecha_nacimiento = forms.DateField(widget=forms.TextInput(attrs=date_dict))    
    telefono = forms.CharField(required=False)
    movil = forms.CharField(required=False)
    #pais = forms.ChoiceField(widget=forms.Select(attrs=pais_dict))
    departamento = forms.ChoiceField(widget=forms.Select(attrs=depto_dict))
    ciudad = forms.ModelChoiceField(City.objects, widget=forms.Select(attrs=ciudad_dict))
    
    def datos_usuario(self, empresario):       
        self.fields['nombre'].initial = empresario.nombre
        self.fields['apellido'].initial = empresario.apellido        
        self.fields['telefono'].initial = empresario.telefono
        self.fields['movil'].initial = empresario.movil
        self.fields['fecha_nacimiento'].initial = empresario.fecha_nacimiento
    
    def save(self, usuario):
        
        ciudad = City.objects.select_related().get(pk=int(self.cleaned_data['ciudad'].codigo))
        departamento = ciudad.admin_area
        pais = departamento.country
        
        
        empresario = Empresario.objects.get(user= usuario)
        empresario.nombre = nombre=self.cleaned_data['nombre']
        empresario.apellido = self.cleaned_data['apellido']
        empresario.fecha_nacimiento=self.cleaned_data['fecha_nacimiento']
        empresario.telefono=self.cleaned_data['telefono']
        empresario.movil=self.cleaned_data['movil']
        empresario.pais=pais
        empresario.departamento=departamento
        empresario.ciudad=ciudad 
        
        empresario.save()
################################################################################       